package com.tanhua.api.mongo;

import com.tanhua.domain.mongo.RecommendUser;
import com.tanhua.domain.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class RecommendUserApiImpl implements RecommendUserApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public RecommendUser findMaxScore(Long toUserId) {
        // 查询缘分值最高的用户
        Query query = Query.query(Criteria.where("toUserId").is(toUserId))
                .with(Sort.by(Sort.Order.desc("score")))
                .skip(0).limit(1);

        return mongoTemplate.findOne(query, RecommendUser.class);
    }

    @Override
    public PageBeanVo findByPage(Integer pageNum, Integer pageSize, Long toUserId) {

        // 计算起始索引
        Integer index = (pageNum - 1) * pageSize + 1; // 排除第一条
        Query query = Query.query(Criteria.where("toUserId").is(toUserId))
                .with(Sort.by(Sort.Order.desc("score")))
                .skip(index).limit(pageSize);

        List<RecommendUser> recommendUserList = mongoTemplate.find(query, RecommendUser.class);

        // 总记录数
        Long counts = mongoTemplate.count(query, RecommendUser.class);

        return new PageBeanVo(pageNum, pageSize, counts, recommendUserList);
    }

    @Override
    public Long findbestUserScore(Long bestUserId, Long toUserId) {
        Query query = Query.query(
                Criteria.where("userId").is(bestUserId)
                        .and("toUserId").is(toUserId)
        );
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);

        if (recommendUser == null) {
            return 60L;
        } else {
            return recommendUser.getScore().longValue();
        }

    }
}
